<?php

namespace app\api\controller\database;

use app\api\controller\Api;
use app\common\database\model\Tables;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;
use util\Format;

class Table extends Api
{
    /**
     * 获取数据库表
     * @return \think\response\Json
     */
    public function index(): \think\response\Json
    {

        $post = $this->request->post();
        $where = [];
        if (!empty($post['keyword'])) $where[] = ['name', 'like', "%{$post['keyword']}%"];

        list($cfg) = Format::pagination($post);

        // $model = new Tables();
        // 实例化db
        $pg = Db::table("tk_tables")->where($where)->order('name')->paginate($cfg);

        $result['list'] = $pg->getCollection();
        $result['pagination'] = Format::pgResult($pg);
        // 获取数据库表字段
        return success($result);
    }

    // 同步表
    public function syncTable(): \think\response\Json
    {
        $tables = Db::query("show tables");

        // 获取数据库名称
        $dbConfig = config('database.connections.mysql');

        $field = 'Tables_in_'.$dbConfig['database'];
        $tables = array_column($tables, $field);

        // 过滤tables中的tk_tables数据
        $tables = array_filter($tables, function($table){
            return $table != 'tk_tables';
        });

        // 获取已经存在的表
        $exists = Db::table('tk_tables')->column('name');

        // 在exists中 但是不在tables中
        $notExists = array_diff($exists, $tables);
        if($notExists){
            Db::table('tk_tables')->where('name', 'in', $notExists)->delete();
        }

        // 过滤已经存在的表
        $tables = array_filter($tables, function($table) use ($exists){
            return !in_array($table, $exists);
        });

        $data = [];
        foreach($tables as $table){
            $data[] = ['name' => $table];
        }
        Db::table('tk_tables')->insertAll($data);

        return success([], '同步成功');
    }

    /**
     * 获取数据库表字段
     * @return \think\response\Json
     */
    public function setTableTitle(): \think\response\Json
    {
        $post = $this->request->post();
        $table = $post['name'];
        $title = $post['title'];

        try {
            Db::table('tk_tables')->where('name', $table)->update(['title' => $title]);
        } catch (DbException $e) {
            return error([],'设置失败');
        }

        return success([], '设置成功');
    }

    /**
     * 获取数据库表字段
     * @return \think\response\Json
     */
    public function fields(): \think\response\Json
    {
        $post = $this->request->post();
        $table = $post['table'];

        $fields = Db::query("show full fields from $table");

        // 提取字段 Field，Type，Comment，Default
        $fields = array_map(function ($field) {
            return [
                'Field' => $field['Field'],
                'Type' => $field['Type'],
                'Comment' => $field['Comment'],
                'Default' => $field['Default'],
            ];
        }, $fields);

        return success($fields);
    }

    /**
     * 获取数据库表字段
     * @return \think\response\Json
     */
    public function readTableForm(): \think\response\Json
    {
        $post = $this->request->post();
        $table = $post['table'];

        try {
            $res = Db::table('tk_table_form')->where('table', $table)->find();
            if ($res) {
                return success(json_decode($res['items'], true));
            } else {
                return success([], '未找到表单');
            }
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            return success([], '未找到表单');
        }
    }

    public function saveTableForm(): \think\response\Json
    {
        $post = $this->request->post();
        $table = $post['table'];
        $items = $post['items'];

        // 表tk_table_form
        // 查询是否存在
        $res = Db::table('tk_table_form')->where('table', $table)->find();
        if ($res) {
            // 执行更新
            try {
                Db::table('tk_table_form')->where('table', $table)->update(['items' => json_encode($items)]);
                // 更新tk_tables表的form字段为1
                Db::table('tk_tables')->where('name', $table)->update(['form' => 1]);
            } catch (DbException $e) {
                return error([], '更新失败');
            }

            return success([], '更新成功');
        } else {
            // 执行插入
            try {
                Db::table('tk_table_form')->insert(['table' => $table, 'items' => json_encode($items)]);
                // 更新tk_tables表的form字段为1
                Db::table('tk_tables')->where('name', $table)->update(['form' => 1]);
            } catch (DbException $e) {
                return error([], '插入失败');
            }

            return success([], '插入成功');
        }

    }


    /**
     * 获取数据库表字段
     * @return \think\response\Json
     */
    public function readTableSearch(): \think\response\Json
    {
        $post = $this->request->post();
        $table = $post['table'];

        try {
            $res = Db::table('tk_table_search')->where('table', $table)->find();
            if ($res) {
                return success(json_decode($res['items'], true));
            } else {
                return error([], '未找到搜索配置项');
            }
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            return success([], '未找到搜索配置项');
        }
    }

    public function saveTableSearch(): \think\response\Json
    {
        $post = $this->request->post();
        $table = $post['table'];
        $items = $post['items'];

        // 表tk_table_form
        // 查询是否存在
        $res = Db::table('tk_table_search')->where('table', $table)->find();
        if ($res) {
            // 执行更新
            try {
                Db::table('tk_table_search')->where('table', $table)->update(['items' => json_encode($items)]);
                // 更新tk_tables表的search字段为1
                Db::table('tk_tables')->where('name', $table)->update(['search' => 1]);
            } catch (DbException $e) {
                return error([], '更新失败');
            }

            return success([], '更新成功');
        } else {
            // 执行插入
            try {
                Db::table('tk_table_search')->insert(['table' => $table, 'items' => json_encode($items)]);
                // 更新tk_tables表的search字段为1
                Db::table('tk_tables')->where('name', $table)->update(['search' => 1]);
            } catch (DbException $e) {
                return error([], '插入失败');
            }

            return success([], '插入成功');
        }
    }

    // 获取列表配置
    public function getTableList(): \think\response\Json
    {
        $post = $this->request->post();
        $table = $post['table'];
        if (empty($table)) return error([], '参数错误');

        try {
            $row = Db::table('tk_table_list')->where('table', $table)->find();
            if ($row) {
                $row['items'] = json_decode($row['items'], true);
                return success($row);
            } else {
                return error([], '暂无列表配置');
            }
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            return error([],'暂无列表配置');
        }
    }

    // 添加或者更新列表配置
    public function setTableList(): \think\response\Json
    {
        $post = $this->request->post();
        $table = $post['table'];
        $items = $post['fields'];

        // 表tk_table_form
        // 查询是否存在
        $res = Db::table('tk_table_list')->where('table', $table)->find();
        if ($res) {
            // 执行更新
            try {
                Db::table('tk_table_list')->where('table', $table)->update(['items' => json_encode($items)]);
                // 更新tk_tables表的list字段为1
                Db::table('tk_tables')->where('name', $table)->update(['list' => 1]);
            } catch (DbException $e) {
                return error([], '更新失败');
            }

            return success([], '更新成功');
        } else {

            // 执行插入
            try {
                Db::table('tk_table_list')->insert(['table' => $table, 'items' => json_encode($items)]);
                // 更新tk_tables表的list字段为1
                Db::table('tk_tables')->where('name', $table)->update(['list' => 1]);
            } catch (DbException $e) {
                return error([], $e->getMessage());
            }

            return success([], '插入成功');
        }
    }

    
    /**
     * 获取模型信息
     */
    public function readTableModel(): \think\response\Json
    {
        $post = $this->request->post();
        $model = $post['table'];
        // 获取模型信息
        $model = Db::table('tk_table_model')->where('table', $model)->find();

        return success($model);
    }

    /**
     * 获取模型信息
     */
    public function setTableModel(): \think\response\Json
    {
        $post = $this->request->post();
        $table = $post['table'];
        $namespace = $post['namespace'];
        $name = $post['name'];

        // 查询是否存在
        $res = Db::table('tk_table_model')->where('table', $table)->find();
        if ($res) {
            // 执行更新
            try {
                Db::table('tk_table_model')->where('table', $table)->update(['namespace' => $namespace, 'name' => $name]);
                // 更新tk_tables表的model字段为1
                Db::table('tk_tables')->where('name', $table)->update(['model' => 1]);
            } catch (DbException $e) {
                return error([], '更新失败');
            }
        } else {
            // 执行插入
            try {
                Db::table('tk_table_model')->insert(['table' => $table, 'namespace' => $namespace, 'name' => $name]);
                // 更新tk_tables表的model字段为1
                Db::table('tk_tables')->where('name', $table)->update(['model' => 1]);
            } catch (DbException $e) {
                return error([], '插入失败');
            }
        }
    
        return success([], '操作成功');
    }
}